package com.yunyike.app.util;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.formula.functions.T;

public class Common {
    private static int weeks = 0;// 用来全局把握 上一周,本周,下一周的周数变更
    public static final int WEEK_DAYNUM = 7;

    /**
     * 获取文件后缀格式
     * 
     * @param filename
     * @return 文件后缀格式 eg: (.jpg)
     */
    public static String getFileExt(String filename) {
        if (org.apache.commons.lang.StringUtils.isEmpty(filename) || filename.lastIndexOf(".") == -1) {
            return "";
        }
        String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        return extName;
    }

    /**
     * 获取文件后缀格式
     * 
     * @param filename
     * @return 文件后缀格式 eg: (jpg)
     */
    public static String getFileExt2(String filename) {
        if (org.apache.commons.lang.StringUtils.isEmpty(filename) || filename.lastIndexOf(".") == -1) {
            return "";
        }
        String extName = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return extName;
    }

    /**
     * 获取项目 请求BASE路径
     * 
     * @param request
     * @return
     */
    public static String getRootRequestPath(HttpServletRequest request) {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
                + "/";
        return basePath;
    }

    /**
     * 获取项目 物理根路径
     * 
     * @param request
     * @return
     */
    public static String getRealPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }

    /**
     * 获取项目 物理根路径
     * 
     * @param orgFileName
     *            原文件名
     * @return
     */
    public static String getNewFileName(String orgFileName, String ntype) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = (!org.apache.commons.lang.StringUtils.isEmpty(ntype) ? ntype + "_" : "")
                + sdf.format(new Date()) + getFileExt(orgFileName);
        return fileName;
    }

    /**
     * 格式化价钱.
     * 
     * @param price
     *            价格
     * @return 格式后的价格
     */
    public static BigDecimal priceFormat(BigDecimal price) {
        BigDecimal pic = new BigDecimal(0);
        if (null != price) {
            DecimalFormat priceFormat = new DecimalFormat("0.00");
            String formatPrice = priceFormat.format(price);
            pic = new BigDecimal(formatPrice);
        }
        return pic;
    }

    /*********************** 时间相关 **************************/
    /**
     * 获取昨天日期
     * 
     * @return
     */
    public static String getBeforeDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1); // 得到前一天
        date = calendar.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(date);
    }

    public static String getToDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // calendar.add(Calendar.DATE); // 得到前一天
        date = calendar.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(date);
    }

    /**
     * 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss'(24小时制)<br>
     * 如Sat May 11 17:24:21 CST 2002 to '2002-05-11 17:24:21'<br>
     * 
     * @param time
     *            Date 日期<br>
     * @return String 字符串<br>
     */
    public static String dateToString(Date time) {
        if (time == null) {
            return "";
        }
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ctime = formatter.format(time);

        return ctime;
    }

    /**
     * 获得上周礼拜一的日期
     * 
     * @return string
     * @throws Exception
     */
    public static String getPreviousWeekMonday() throws Exception {
        weeks = 0;
        weeks--;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + WEEK_DAYNUM * weeks);
        Date monday = currentDate.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preMonday = df.format(monday);
        return preMonday;
    }

    /**
     * 获得上周礼拜日的日期
     * 
     * @return string
     * @throws Exception
     */
    public static String getWeekMonday() throws Exception {
        weeks = 0;
        weeks--;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + weeks + 1);
        Date monday = currentDate.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preMonday = df.format(monday);
        return preMonday;
    }

    /**
     * 获合适前日期与本周日相差的天数
     * 
     * @return string
     * @throws Exception
     */
    private static int getMondayPlus() throws Exception {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天,礼拜日是第一天,礼拜二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因为按中国礼拜一作为第一天所以这里减1
        if (dayOfWeek == 1) {
            return 0;
        } else {
            return 1 - dayOfWeek;
        }
    }

    /*************************** 表格相关 *************************/
    public static Map<String, Object> geneBookBegin(String workName, String[] headTitle) {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        HSSFWorkbook workbook = new HSSFWorkbook();// 声明一个工作薄
        HSSFSheet sheet = workbook.createSheet(workName);// 生成一个表格
        HSSFRow row = sheet.createRow((int) 0);
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.YELLOW.index);
        sheet.setDefaultColumnWidth(20);
        HSSFCell cell = null;
        for (int i = 0; i < headTitle.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(headTitle[i]);
            cell.setCellStyle(style);
        }
        map.put("workbook", workbook);
        map.put("sheet", sheet);
        map.put("row", row);
        return map;
    }

    public static Map<String, Object> geneBookBeginDouble(String workName, String[] headTitle, String[] fistTitle,
            int[] spanArr) {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        HSSFWorkbook workbook = new HSSFWorkbook();// 声明一个工作薄
        HSSFSheet sheet = workbook.createSheet(workName);// 生成一个表格
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.YELLOW.index);
        HSSFCellStyle style0 = workbook.createCellStyle();
        style0.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        sheet.setDefaultColumnWidth(20);
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;
        for (int i = 0; i < headTitle.length; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(style0);
        }
        if (spanArr != null && spanArr.length > 0) {
            int cellNum = 0;
            for (int i = 0; i < spanArr.length; i++) {
                int cellEnd = spanArr[i] - 1;
                addMergedRegion(sheet,0, 0, cellNum, cellNum + cellEnd, style);
                sheet.getRow(0).getCell(cellNum).setCellValue(fistTitle[i]);
                cellNum = cellNum + spanArr[i];
            }
        }
        row = sheet.createRow(1);
        for (int i = 0; i < headTitle.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(headTitle[i]);
            cell.setCellStyle(style);
        }
        map.put("workbook", workbook);
        map.put("sheet", sheet);
        map.put("row", row);
        return map;
    }

    public static void writeBookEnd(String workName, HttpServletResponse response, HSSFWorkbook workbook)
            throws Exception {
        OutputStream os = null;
        String filename = workName;
        os = response.getOutputStream();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        filename = java.net.URLEncoder.encode(filename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String(filename.getBytes("UTF-8"), "GBK") + ".xls");
        response.setContentType("application/msexcel");// 定义输出类型
        workbook.write(os);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    /**
     * 生成单元格的列
     * 
     * @param row
     * @param cellNum
     * @param cellValue
     * @param styleRow
     */
    @SuppressWarnings("deprecation")
    public static void geneCell(HSSFRow row, Short cellNum, String cellValue, HSSFCellStyle styleRow) {
        HSSFCell cell = row.createCell(cellNum);
        cell.setCellValue(cellValue);
        cell.setCellStyle(styleRow);
    }

    @SuppressWarnings("deprecation")
    public static void addMergedRegion(HSSFSheet sheet, int rowNumStart, int rowNumEnd, int celStart, int celEnd,
            HSSFCellStyle styleRow) {
        CellRangeAddress cellRangeAddress = new CellRangeAddress(rowNumStart, rowNumEnd, celStart, celEnd);
        sheet.addMergedRegion(cellRangeAddress);
        // styleRow.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//
        // 垂直居中对齐
        // sheet.getRow(rowNumStart).getCell(celStart).setCellStyle(styleRow);
    }

    /**
     * 得到Excel表中的值
     * 
     * @param hssfCell
     *            Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    public static String getValue(HSSFRow hssfRow,int column) {
    	HSSFCell hssfCell = hssfRow.getCell(column);
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
        	if(hssfCell.getStringCellValue()==null)return "";
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
    public static String validate( Object obj,Class clazz,Integer len,boolean notNull){
 	   
 	   if(notNull&&obj==null){
 		   return "不能为空";
 	   }
 	   try{
 		   if(obj!=null){
 			   if(clazz.equals(String.class)){
 				   if(obj.toString().matches("^[\u4E00-\u9FA5]+$")){
 					  len = len/2;
 				   }
 				   if(obj.toString().length()>len)return "长度超出数据库字段范围";
 			   }
 		   }
 	   }catch(Exception e){
 		   e.printStackTrace();
 		   return "校验时发生异常";
 	   }
 	   return "";
    }
    
}
